import React, { useState } from 'react';
import './PDFProcess.css';

const API_BASE = 'http://localhost:5001/api/pdf';

function fileListToArray(fileList) {
  return Array.prototype.slice.call(fileList);
}

export default function PDFProcess() {
  const [mergeFiles, setMergeFiles] = useState([]);
  const [splitFile, setSplitFile] = useState(null);
  const [encryptFile, setEncryptFile] = useState(null);
  const [decryptFile, setDecryptFile] = useState(null);
  const [password, setPassword] = useState('');
  const [result, setResult] = useState(null);
  const [splitPages, setSplitPages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState('merge');

  // 通用下载
  const download = (blob, filename) => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
  };

  // 合并
  const handleMerge = async (e) => {
    e.preventDefault();
    if (!mergeFiles.length) return;
    setLoading(true);
    const formData = new FormData();
    mergeFiles.forEach(f => formData.append('pdfs', f));
    const res = await fetch(`${API_BASE}/merge`, { method: 'POST', body: formData });
    const blob = await res.blob();
    setLoading(false);
    download(blob, 'merged.pdf');
  };

  // 拆分
  const handleSplit = async (e) => {
    e.preventDefault();
    if (!splitFile) return;
    setLoading(true);
    const formData = new FormData();
    formData.append('pdf', splitFile);
    const res = await fetch(`${API_BASE}/split`, { method: 'POST', body: formData });
    const data = await res.json();
    setLoading(false);
    setSplitPages(data.pages);
  };

  // 加密
  const handleEncrypt = async (e) => {
    e.preventDefault();
    if (!encryptFile || !password) return;
    setLoading(true);
    const formData = new FormData();
    formData.append('pdf', encryptFile);
    formData.append('password', password);
    const res = await fetch(`${API_BASE}/encrypt`, { method: 'POST', body: formData });
    const blob = await res.blob();
    setLoading(false);
    download(blob, 'encrypted.pdf');
  };

  // 解密
  const handleDecrypt = async (e) => {
    e.preventDefault();
    if (!decryptFile || !password) return;
    setLoading(true);
    const formData = new FormData();
    formData.append('pdf', decryptFile);
    formData.append('password', password);
    const res = await fetch(`${API_BASE}/decrypt`, { method: 'POST', body: formData });
    const blob = await res.blob();
    setLoading(false);
    download(blob, 'decrypted.pdf');
  };

  return (
    <div className="pdf-process-container">
      <div className="pdf-process-header">PDF处理工具</div>
      <div className="pdf-process-tabs">
        <button className={tab === 'merge' ? 'active' : ''} onClick={() => setTab('merge')}>PDF合并</button>
        <button className={tab === 'split' ? 'active' : ''} onClick={() => setTab('split')}>PDF拆分</button>
        <button className={tab === 'encrypt' ? 'active' : ''} onClick={() => setTab('encrypt')}>PDF加密</button>
        <button className={tab === 'decrypt' ? 'active' : ''} onClick={() => setTab('decrypt')}>PDF解密</button>
      </div>
      <div className="pdf-process-content">
        {tab === 'merge' && (
          <form onSubmit={handleMerge} className="pdf-form">
            <label>选择要合并的PDF文件（可多选）</label>
            <input type="file" accept="application/pdf" multiple onChange={e => setMergeFiles(fileListToArray(e.target.files))} />
            <button type="submit" disabled={loading}>{loading ? '处理中...' : '开始合并'}</button>
          </form>
        )}
        {tab === 'split' && (
          <form onSubmit={handleSplit} className="pdf-form">
            <label>选择要拆分的PDF文件</label>
            <input type="file" accept="application/pdf" onChange={e => setSplitFile(e.target.files[0])} />
            <button type="submit" disabled={loading}>{loading ? '处理中...' : '开始拆分'}</button>
            {splitPages.length > 0 && (
              <div className="split-pages-list">
                <div>拆分结果：</div>
                {splitPages.map((p, i) => (
                  <a key={i} href={`data:application/pdf;base64,${p.base64}`} download={p.filename}>下载 {p.filename}</a>
                ))}
              </div>
            )}
          </form>
        )}
        {tab === 'encrypt' && (
          <form onSubmit={handleEncrypt} className="pdf-form">
            <label>选择要加密的PDF文件</label>
            <input type="file" accept="application/pdf" onChange={e => setEncryptFile(e.target.files[0])} />
            <label>设置密码</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)} />
            <button type="submit" disabled={loading}>{loading ? '处理中...' : '开始加密'}</button>
          </form>
        )}
        {tab === 'decrypt' && (
          <form onSubmit={handleDecrypt} className="pdf-form">
            <label>选择要解密的PDF文件</label>
            <input type="file" accept="application/pdf" onChange={e => setDecryptFile(e.target.files[0])} />
            <label>输入密码</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)} />
            <button type="submit" disabled={loading}>{loading ? '处理中...' : '开始解密'}</button>
          </form>
        )}
      </div>
    </div>
  );
} 